package com.example.questionnaires.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.questionnaires.entity.Questionnaire;
import com.example.questionnaires.entity.QuestionnaireRecord;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.mapper.QuestionnaireMapper;
import com.example.questionnaires.mapper.QuestionnaireRecordMapper;
import com.example.questionnaires.mapper.UserMapper;
import com.example.questionnaires.service.DashboardService;
import com.example.questionnaires.vo.DashboardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionnaireRecordMapper recordMapper;

    @Override
    public DashboardVO getStats() {
        DashboardVO vo = new DashboardVO();

        // 1. 问卷总数
        Long questionnaireCount = questionnaireMapper.selectCount(
            new LambdaQueryWrapper<Questionnaire>()
                .eq(Questionnaire::getStatus, 1)
        );
        vo.setQuestionnaireCount(questionnaireCount);

        // 2. 用户总数（不包括管理员）
        Long userCount = userMapper.selectCount(
            new LambdaQueryWrapper<User>()
                .eq(User::getStatus, 1)
                .eq(User::getRole, 2)
        );
        vo.setUserCount(userCount);

        // 3. 今日提交数
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        Long todaySubmitCount = recordMapper.selectCount(
            new LambdaQueryWrapper<QuestionnaireRecord>()
                .between(QuestionnaireRecord::getCreateTime, todayStart, todayEnd)
        );
        vo.setTodaySubmitCount(todaySubmitCount);

        // 4. 总访问量（所有问卷的访问量之和）
        Long totalVisits = questionnaireMapper.selectList(
            new LambdaQueryWrapper<Questionnaire>()
                .eq(Questionnaire::getStatus, 1)
        ).stream()
            .mapToLong(Questionnaire::getViewCount)
            .sum();
        vo.setTotalVisits(totalVisits);

        return vo;
    }
} 